package com.itheima.mongodb.mapper;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.pojo.RecommendUser;
import com.itheima.commons.pojo.UserLike;
import com.itheima.commons.pojo.Visitors;
import com.itheima.commons.vo.PageResult;
import com.itheima.interfaces.TanHuaApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class TanHuaMapperImpl implements TanHuaApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser todayBestByToUserId(Long toUserId) {

        RecommendUser recommendUser = mongoTemplate.findOne(Query.query(Criteria.where("toUserId").is(toUserId))
                        .with(Sort.by(Sort.Order.desc("score")))
                        .with(PageRequest.of(0, 1))
                , RecommendUser.class);

        return recommendUser;
    }

    @Override
    public PageResult recommendationAllFriend(Integer page, Integer pagesize, Long toUserId) {

        List<RecommendUser> userList = mongoTemplate.find(Query.query(Criteria.where("toUserId").in(toUserId))
                        .with(PageRequest.of(page - 1, pagesize))
                , RecommendUser.class);
        long count = mongoTemplate.count(Query.query(Criteria.where(null)), RecommendUser.class);
        PageResult pageResult = new PageResult(page, pagesize, count, userList);
        return pageResult;
    }

    @Override
    public RecommendUser findScoreByRecommend(Long id, Long toUserId) {

        RecommendUser recommendUser = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(id).and("toUserId").is(toUserId)), RecommendUser.class);
        return recommendUser;
    }

    @Override
    public List<RecommendUser> selectByToUserId(Long userId) {
        AggregationResults<RecommendUser> recommendUsers = mongoTemplate.aggregate(Aggregation.newAggregation(RecommendUser.class, Aggregation.sample(20)), RecommendUser.class);
        return recommendUsers.getMappedResults();
    }

    @Override
    public void loveCard(UserLike userLike) {
        mongoTemplate.save(userLike);
    }

    @Override
    public void savePersonInfo(Visitors visitors) {
        mongoTemplate.save(visitors);
    }


}
